package clickhouse.service.impl;

import clickhouse.service.ITemplatePreparedStatement;
import clickhouse.service.ITemplateStatement;
import clickhouse.util.StrUtil;
import ru.yandex.clickhouse.ClickHouseConnection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ClickHouseWrap implements AutoCloseable{
    ClickHouseConnection connection ;
    protected ClickHouseWrap(ClickHouseConnection connection) {
        this.connection=connection;
    }

    @Override
    public void close() {
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    protected  <T> T query(String sql, ITemplateStatement<T> templateResultSet){
        try ( Statement statement = connection.createStatement();
              ResultSet rs= StrUtil.isNull(sql)?null:statement.executeQuery(sql);
        ) {
            return templateResultSet.doOperation(statement,rs);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }

    /**
     * 带参数查询
     * @param prepareSql
     */
    protected <T> T preparedQuery(String prepareSql, ITemplatePreparedStatement<T> templatePreparedStatement){
        try (PreparedStatement ps = connection.prepareStatement(prepareSql);
        ) {
             return templatePreparedStatement.doOperation(ps);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
